package org.testtools.connector.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.testtools.connector.Connector;

public class JDBCConnector implements Connector {

	private boolean autocommit = false;

	private String driver = null;

	private String password = null;

	private String url = null;

	private String username = null;

	public JDBCConnector(String driver, String url, String username,
			String password, boolean autocommit) {
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
		this.autocommit = autocommit;
	}

	public static Connection getConnection(String driver, String url,
			String username, String password) throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		return getConnection(driver, url, username, password, true);
	}

	public static Connection getConnection(String driver, String url,
			String username, String password, boolean autocommit)
			throws SQLException, InstantiationException,
			IllegalAccessException, ClassNotFoundException {

		if (driver == null) {
			return null;
		}

		Class.forName(driver).newInstance();
		final Connection conn = DriverManager.getConnection(url, username,
				password);

		if (!autocommit) {
			conn.setAutoCommit(false);
		}

		return conn;
	}

	public static boolean testConnection(String driver, String url,
			String username, String password) throws Exception {

		Connection conn = getConnection(driver, url, username, password, true);

		if (conn != null) {
			conn.close();
			return true;
		}

		return false;
	}

	@Override
	public Connection getConnection() throws Exception {
		return getConnection(driver, url, username, password, autocommit);
	}

	@Override
	public boolean testConnection() throws Exception {
		return testConnection(driver, url, username, password);
	}
}
